#include "mywebview.h"
#include "useragent.h"
#include "myspaces.h"

myWebInspector::myWebInspector(QWidget* parent)
    : QWebInspector(parent)
{
}

void myWebInspector::showEvent(QShowEvent* event)
{
    emit shEvent(true);
    QWebInspector::showEvent(event);
}

void myWebInspector::hideEvent(QHideEvent* event)
{
    QWebInspector::hideEvent(event);
}

myWebPage::myWebPage(QObject *parent):
    QWebPage(parent),
    userAgent(createuseragent()),
    m_JSApi(new JavaScriptApi(this))
{
    setNetworkAccessManager(mySpaces::networkAccessManager());
    setForwardUnsupportedContent(true);
    connect(this, SIGNAL(unsupportedContent(QNetworkReply*)),this, SLOT(handleUnsupportedContent(QNetworkReply*)));
    connect(this, SIGNAL(frameCreated(QWebFrame*)), this, SLOT(addExternalBinding(QWebFrame*)));
    addExternalBinding(mainFrame());
}

void myWebPage::addExternalBinding(QWebFrame *frame)
{
    if(frame==0)
    {
        frame = qobject_cast<QWebFrame*>(sender());
        if(frame->url().scheme() == QLatin1String("myspaces"))
        {
            frame->addToJavaScriptWindowObject(QString("myspaces"), m_JSApi);
        }
    }
    else
    {
        connect(frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addExternalBinding()));
    }
}

bool myWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request,
                                      NavigationType type)
{
    if(request.url().scheme() == "myspaces")
        return true;
    if(!request.url().host().endsWith("spaces.ru")
            && request.url().host()!=QString("localhost"))
    {
        QDesktopServices::openUrl(request.url());
        return false;
    }
    bool accepted = QWebPage::acceptNavigationRequest(frame, request, type);
    return accepted;
}

void myWebPage::InspectElement()
{
}

QString myWebPage::userAgentForUrl(const QUrl&) const
{
    return userAgent;
}

myWebView::myWebView(QWidget *parent):
    QWebView(parent),
    m_page(new myWebPage(this)),
    newTabUrl(new QUrl(NULL))
{
    setPage(m_page);
    connect(page(), SIGNAL(downloadRequested(const QNetworkRequest &)),
            this, SLOT(downloadRequested(const QNetworkRequest &)));
}

void myWebView::mousePressEvent(QMouseEvent *event)
{
    switch(event->button())
    {
    case Qt::XButton1: back();; break;
    case Qt::XButton2: forward(); break;
    default: QWebView::mousePressEvent(event);
    }

}

void myWebView::downloadRequested(const QNetworkRequest &request)
{
    m_page->DownloadFile(request.url());
}

void myWebPage::handleUnsupportedContent(QNetworkReply *reply)
{
    DownloadFile(reply->url());
}

int myWebPage::DownloadFile(const QUrl &url)
{
    mySpaces::downloadManager()->downloadFile(url);
    return 0;
}

void myWebView::openLinkInNewTab()
{
    if(newTabUrl)
    {
        emit signalOpenLinkInNewTab(*newTabUrl);
    }
    delete newTabUrl;
    newTabUrl = new QUrl(NULL);
}

void myWebView::contextMenuEvent(QContextMenuEvent *event)
{
    QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos());
    if (!r.linkUrl().isEmpty()) {
        *newTabUrl = r.linkUrl();
        QMenu menu(this);
        menu.addAction(pageAction(QWebPage::OpenLink));
        menu.addAction(tr("Open link in new tab"), this, SLOT(openLinkInNewTab()));
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addAction(pageAction(QWebPage::CopyLinkToClipboard));
        menu.addSeparator();
        if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled))
            menu.addAction(pageAction(QWebPage::InspectElement));
        menu.exec(mapToGlobal(event->pos()));
        return;
    }
    QWebView::contextMenuEvent(event);
}

void myWebView::load(const QUrl &url)
{
    if (url.scheme() == "javascript") {
        page()->mainFrame()->evaluateJavaScript(url.toString());
        return;
    }

    if (url.scheme() == "data" || url.scheme() == "qrc") {
        QWebView::load(url);
        emit urlChanged(url);
        return;
    }

    if (isUrlValid(url)) {
        QWebView::load(url);
        emit urlChanged(url);
        return;
    }

    if (QFile::exists(url.toLocalFile())) {
        QWebView::load(url);
        emit urlChanged(url);
    }
}

bool myWebView::isUrlValid(const QUrl &url)
{
    if (url.scheme() == "myspaces") {
        return true;
    }

    if (url.isValid() && !url.host().isEmpty() && !url.scheme().isEmpty()) {
        return true;
    }
    return false;
}
